package com.sam.im.heiqun.uis.activities;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.GetmoneyEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.PayTransferEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import io.socket.client.Ack;
import io.socket.client.Socket;
import com.sam.im.heiqun.utils.StringUtils;

public class PayActivity extends BaseSwipeBackActivity {

    private final int RESULT_EDIT_MONEY = 100;

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.pre_tv_title)
    TextView tvTitle;
    @BindView(R.id.tvdiscrible)
    TextView tvdiscrible;
    @BindView(R.id.bt_sure)
    Button btSure;
    @BindView(R.id.tv_amout)
    TextView tvAmout;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_payorget)
    TextView tvPayorGet;
    @BindView(R.id.view1)
    LinearLayout view1 ;
    @BindView(R.id.view2)
    LinearLayout view2 ;
    private GetmoneyEntivity getmoneyEntivity;
    private PayTransferEntivity payTransferEntivity;
    private String amount;
    private String receiptId;
    private PGService mPgSercice;
    private AlertDialog payDialog;
    private Double balance;
    PasswordEditText payPSD;
    private static Socket mSocket;
    private ImMessage topay;
    private static final   int SEND_ERROR = 1111 ;
    private static final   int SEND_OK = 0000 ;
    private SendMessageHandler sendMessageHandler;
    private String receiptHeadUrl;
    private ImMessage sendpaymessage;

    String money ;
    String paymoney;

    @Override
    public int getContentViewId() {
        return R.layout.activity_pay;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.pay_money);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//        EventBus.getDefault().register(this);
        money = getIntent().getStringExtra("money");
        paymoney = getIntent().getStringExtra("paymoney");
        topay = (ImMessage) getIntent().getSerializableExtra("topay");
        sendMessageHandler = new SendMessageHandler(this);
        if (money != null && !StringUtils.isEmpty(money)) {
            try {
                tvTitle.setText(getResources().getString(R.string.pay_money));
                tvPayorGet.setText(getResources().getString(R.string.pay_money));
                getmoneyEntivity = new Gson().fromJson(money, GetmoneyEntivity.class);
                amount = RequestRSAUtils.getRsaContent(getmoneyEntivity.getAmount());
                if (isGo()){//去输入
                    Intent intent = new Intent(PayActivity.this,PayInPutMoneyActivity.class);
                    intent.putExtra("money",money);
                    startActivityForResult(intent,RESULT_EDIT_MONEY);
                    return;
                }
                receiptHeadUrl = getmoneyEntivity.getReceiptHeadUrl();
                receiptId = getmoneyEntivity.getReceiptId();
                String receiptName = getmoneyEntivity.getReceiptName();
                GlideUtils.loadImage(this, receiptHeadUrl, imgIcon);
                tvdiscrible.setText(receiptName);
                tvAmout.setText(" ￥" + amount);
                final double amountint = Double.parseDouble(amount);
                mPgSercice = PGService.getInstance();
                mPgSercice.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
                    @Override
                    protected void onResultError(ApiException ex) {
                        showToast(getResources().getString(R.string.net_visit_exception));
                    }

                    @Override
                    public void onNext(String s) {
                        balance = Double.parseDouble(s);
                        if (amountint > balance) {
                            btSure.setText(getResources().getString(R.string.yue_nozu));
                            btSure.setBackgroundResource(R.drawable.shape_sure_bt_false);
                            btSure.setEnabled(false);
                        }
                        tvBalance.setText(getResources().getString(R.string.yu_e_1) + s + getResources().getString(R.string.yuan));
                    }
                });
            } catch (Exception e) {
e.printStackTrace();
            }
        }
        if (topay != null) {
            tvTitle.setText(getResources().getString(R.string.pay_money));
            tvPayorGet.setText(getResources().getString(R.string.pay_money));
            amount = RequestRSAUtils.getRsaContent(topay.getContent());
            if (isGo()){//去输入
                Intent intent = new Intent(PayActivity.this,PayInPutMoneyActivity.class);
                intent.putExtra("topay",topay);
                startActivityForResult(intent,RESULT_EDIT_MONEY);
                return;
            }
            receiptHeadUrl = topay.getImageIconUrl();
            receiptId = topay.getDestid()+"";
            String receiptName = topay.getFromname();
            GlideUtils.loadImage(this, receiptHeadUrl, imgIcon);
            tvdiscrible.setText(receiptName);
            tvAmout.setText(" ￥" + amount);
            final double amountint = Double.parseDouble(amount);
            mPgSercice = PGService.getInstance();
            mPgSercice.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
                @Override
                protected void onResultError(ApiException ex) {
                    showToast(getResources().getString(R.string.net_visit_exception));
                }

                @Override
                public void onNext(String s) {
                    balance = Double.parseDouble(s);
                    if (amountint > balance) {
                        btSure.setText(getResources().getString(R.string.yue_nozu));
                        btSure.setBackgroundResource(R.drawable.shape_sure_bt_false);
                        btSure.setEnabled(false);
                    }
                    tvBalance.setText(getResources().getString(R.string.yu_e_1) + s + getResources().getString(R.string.yuan));
                }
            });
        }
        if (paymoney != null && !StringUtils.isEmpty(paymoney)) {
            try {
                mSocket = App.socket;
                tvTitle.setText(getResources().getString(R.string.get_money));
                tvPayorGet.setText(getResources().getString(R.string.get_money));
                tvBalance.setVisibility(View.GONE);
                payTransferEntivity = new Gson().fromJson(paymoney, PayTransferEntivity.class);
                amount = RequestRSAUtils.getRsaContent(payTransferEntivity.getAmount());
                if (isGo()){//去输入
                    Intent intent = new Intent(PayActivity.this,PayInPutMoneyActivity.class);
                    intent.putExtra("paymoney",paymoney);
                    startActivityForResult(intent,RESULT_EDIT_MONEY);
                    return;
                }
                receiptId = payTransferEntivity.getPaymentId();
                String paymentName = payTransferEntivity.getPaymentName();
                String paymentHeadUrl = payTransferEntivity.getPaymentHeadUrl();
                GlideUtils.loadImage(this, paymentHeadUrl, imgIcon);
                tvdiscrible.setText(paymentName);
                tvAmout.setText(" ￥" + amount);
                btSure.setBackgroundResource(R.drawable.shape_sure_bt);
                btSure.setEnabled(true);
            } catch (Exception e) {

            }
        }
    }

    private boolean isGo(){
        try {
            if (Integer.parseInt(amount) <= 0){
                return true ;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false ;
    }
    private void initMoneyView(String editmoney){
        if (money != null && !StringUtils.isEmpty(money)) {
            try {
                tvTitle.setText(getResources().getString(R.string.pay_money));
                tvPayorGet.setText(getResources().getString(R.string.pay_money));
                getmoneyEntivity = new Gson().fromJson(money, GetmoneyEntivity.class);
                getmoneyEntivity.setAmount(editmoney);
                amount = getmoneyEntivity.getAmount();
                receiptHeadUrl = getmoneyEntivity.getReceiptHeadUrl();
                receiptId = getmoneyEntivity.getReceiptId();
                String receiptName = getmoneyEntivity.getReceiptName();
                GlideUtils.loadImage(this, receiptHeadUrl, imgIcon);
                tvdiscrible.setText(receiptName);
                tvAmout.setText(" ￥" + amount);
                final double amountint = Double.parseDouble(amount);
                mPgSercice = PGService.getInstance();
                mPgSercice.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
                    @Override
                    protected void onResultError(ApiException ex) {
                        showToast(getResources().getString(R.string.net_visit_exception));
                    }

                    @Override
                    public void onNext(String s) {
                        balance = Double.parseDouble(s);
                        if (amountint > balance) {
                            btSure.setText(getResources().getString(R.string.yue_nozu));
                            btSure.setBackgroundResource(R.drawable.shape_sure_bt_false);
                            btSure.setEnabled(false);
                        }
                        tvBalance.setText(getResources().getString(R.string.yu_e_1) + s + getResources().getString(R.string.yuan));
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (topay != null) {
            tvTitle.setText(getResources().getString(R.string.pay_money));
            tvPayorGet.setText(getResources().getString(R.string.pay_money));
            topay.setContent(editmoney);
            amount = topay.getContent();
            receiptHeadUrl = topay.getImageIconUrl();
            receiptId = topay.getDestid()+"";
            String receiptName = topay.getFromname();
            GlideUtils.loadImage(this, receiptHeadUrl, imgIcon);
            tvdiscrible.setText(receiptName);
            tvAmout.setText(" ￥" + amount);
            final double amountint = Double.parseDouble(amount);
            mPgSercice = PGService.getInstance();
            mPgSercice.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
                @Override
                protected void onResultError(ApiException ex) {
                    showToast(getResources().getString(R.string.net_visit_exception));
                }

                @Override
                public void onNext(String s) {
                    balance = Double.parseDouble(s);
                    if (amountint > balance) {
                        btSure.setText(getResources().getString(R.string.yue_nozu));
                        btSure.setBackgroundResource(R.drawable.shape_sure_bt_false);
                        btSure.setEnabled(false);
                    }
                    tvBalance.setText(getResources().getString(R.string.yu_e_1) + s + getResources().getString(R.string.yuan));
                }
            });
        }
        if (paymoney != null && !StringUtils.isEmpty(paymoney)) {
            try {
                mSocket = App.socket;
                tvTitle.setText(getResources().getString(R.string.get_money));
                tvPayorGet.setText(getResources().getString(R.string.get_money));
                tvBalance.setVisibility(View.GONE);
                payTransferEntivity = new Gson().fromJson(paymoney, PayTransferEntivity.class);
                payTransferEntivity.setAmount(editmoney);
                amount = payTransferEntivity.getAmount();
                receiptId = payTransferEntivity.getPaymentId();
                String paymentName = payTransferEntivity.getPaymentName();
                String paymentHeadUrl = payTransferEntivity.getPaymentHeadUrl();
                GlideUtils.loadImage(this, paymentHeadUrl, imgIcon);
                tvdiscrible.setText(paymentName);
                tvAmout.setText(" ￥" + amount);
                btSure.setBackgroundResource(R.drawable.shape_sure_bt);
                btSure.setEnabled(true);
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case RESULT_EDIT_MONEY :
                if (10 == resultCode){
                    String editmoney = data.getStringExtra("editmoney");
                    initMoneyView(editmoney);
                }
                break;
        }
    }

    @OnClick({R.id.pre_v_back, R.id.bt_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.bt_sure://确认付款
                if (getmoneyEntivity != null|topay!=null) {
                    final UserEntivity user = ToolsUtils.getUser();
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                        showSetPSWdialog();
                        return;
                    }
                    showPayDialog();
                    // ToolsUtils.showToast(PayActivity.this,"功能正在修改中");
                } else if (payTransferEntivity != null) {
                    sendgetmoneyMessage();
                }
                break;
        }
    }
    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(PayActivity.this);
        builder.setTitle(getResources().getString(R.string.tip_psw));
        builder.setMessage(getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(PayActivity.this, NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private  void sendgetmoneyMessage() {
        UserEntivity user = ToolsUtils.getUser();
        if (null==user)return;

        String paymentHeadUrl = user.getHeadUrl();
        //String paymentHeadUrl = payTransferEntivity.getPaymentHeadUrl();
        String paymentName = payTransferEntivity.getPaymentName();
        String amount = payTransferEntivity.getAmount();
        String paymentId = payTransferEntivity.getPaymentId();
        sendpaymessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0,0, UUID.randomUUID().toString(), Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_MAM, Long.parseLong(paymentId),amount, Constant.MESSAGE_TYPR_TRANSFOR_TOPAY,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, ToolsUtils.getMyUserId() + "_" + paymentId, 0, paymentHeadUrl);
        socketSend(sendpaymessage);
    }
    //生成消息对象
   /* public ImMessage getTbub(int version, int devType, int geoId, int type,
                             String msgId, long fromId, int fromType,
                             long destId, String content, int messageType,
                             long sendTime, long receiveTime, int status, String filePath, String uniqueness, float seconds, String imageIconUrl) {
        ImMessage tbub = new ImMessage();
        tbub.setVersion(version);
        tbub.setDevType(devType);
        tbub.setUserVoiceTime(seconds);
        tbub.setType(type);
        tbub.setGeoId(geoId);
        tbub.setMsgId(msgId);
        tbub.setFromid(fromId);
        tbub.setFromType(fromType);
        //tbub.setFileUrl(content);
        tbub.setFilePath(filePath);
        //tbub.setUserVoicePath(content);
        tbub.setDestid(destId);
        if (content.equals("null")){
            content = "null ";
        }
        tbub.setContent(content);
        tbub.setMessageType(messageType);
        tbub.setFromname(ToolsUtils.getUser().getNickName());//设置名字
        tbub.setSendTime(sendTime);
        tbub.setReceiveTime(receiveTime);
        tbub.setStatus(status);
        tbub.setUniqueness(uniqueness);
        tbub.setSendState(Constant.SENDING);
        tbub.setImageIconUrl(imageIconUrl);
        // tbub.save();
        //  ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
        //  IMMessageToJson.ImMessageToMessageEntivity(tbub, Constant.FROM_TYPE_SELF);
        return tbub;
    }*/
    static class SendMessageHandler extends Handler {

        WeakReference<PayActivity> mActivity;//弱引用

        SendMessageHandler(PayActivity activity) {
            mActivity = new WeakReference<PayActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final PayActivity theActivity = mActivity.get();
            if (theActivity != null) {
                switch (msg.what){
                    case SEND_ERROR:

                        break;
                    case SEND_OK:
                        theActivity.btSure.setEnabled(false);
                        theActivity.btSure.setText(theActivity.getResources().getString(R.string.deng_other_pay));
                        theActivity.btSure.setBackgroundResource(R.drawable.shape_sure_bt_false);
                        break;
                }
            }
        }
    }
    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub) {
        new Thread(new Runnable() {
            boolean sendState = false;
            int retryCount = 0;

            @Override
            public void run() {
                    tbub.save();
                    ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                    socketSend(imMessage);

            }
            @TargetApi(Build.VERSION_CODES.KITKAT)
            private void socketSend(final ImMessage imMessage) {
                while (!sendState && retryCount < 10) {
                    mSocket = App.socket;
                    retryCount++;
                    if (mSocket != null) {
                        mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                            @Override
                            public void call(Object... args) {
                                imMessage.setSendState(Constant.COMPLETED);
                                tbub.setSendState(Constant.COMPLETED);
                                if (imMessage.getMessageType()!=Constant.MESSAGE_TYPR_READ){
                                   imMessage.delete();
                                }
                                sendMessageHandler.sendEmptyMessage(SEND_OK);
                                sendState = true;
                            }
                        });
                    }
                    try {
                        Thread.sleep(Constant.SOCKET_SEND_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    private void dopaymoney(String psw) {
        showProgress(getResources().getString(R.string.commit_now));
        String payPsd = MD5.MD532(psw);
        // Log.i("info","支付密码=="+psw);
        String userId=ToolsUtils.getMyUserId();
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("userId", userId);
        json.put("amount", amount);
        json.put("destId", receiptId);
        json.put("payPwd", payPsd);
        String content = RequestRSAUtils.setRsaContent(json);
        mPgSercice.paymoney(content).subscribe(new AbsAPICallback<ValidateEntivity>() {
        //mPgSercice.paymoney(amount, receiptId, ToolsUtils.getMyUserId(), payPsd).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                if (ex != null) {
                    String displayMessage = ex.getDisplayMessage();
                    try {
                        JSONObject object = new JSONObject(displayMessage);
                        JSONObject data = object.getJSONObject("data");
                        String info = data.getString("info");
                        ToolsUtils.showToast(PayActivity.this, info);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                hideProgress();
            }
            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                if (validateEntivity != null) {
                    ToolsUtils.showToast(PayActivity.this, validateEntivity.getInfo());
                    JSONObject obj = new JSONObject();
                    try {
                        obj.put("amt",amount+"");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0,ChatRecyclerAdapter.TO_USER_PAYFOR, UUID.randomUUID().toString(), Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_SYS, Long.parseLong(receiptId),obj.toString(), Constant.MESSAGE_TYPR_TOPAYFOR,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, null, ToolsUtils.getMyUserId() + "___", 0, receiptHeadUrl);
                    imMessage.save();
                    MessageEntivity messageEntivity = IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
                    EventBus.getDefault().post(messageEntivity);
                    hideProgress();
                    finish();
                } else {
                    ToolsUtils.showToast(PayActivity.this, getResources().getString(R.string.pay_fail));
                }
                hideProgress();
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onImMessageEvent(final ImMessage imMessage) {
        if (imMessage.getMessageType()==Constant.MESSAGE_TYPR_TRANSFOR_ISCOME){
            view1.setVisibility(View.GONE);
            view2.setVisibility(View.VISIBLE);
        }
    }
    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(String pwd) {
        String payPsd = MD5.MD532(pwd);
        mPgSercice.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_verify_defeat));
            }

            @Override
            public void onNext(String validateEntivity) {
                //  dopaymoney();
               /* String money = sendMoney.getText().toString().trim();
                String liuyan = message.getText().toString().trim();
                String num = packageCount.getText().toString().trim();
                if (null == liuyan || "".equals(liuyan)) {
                    liuyan = getResources().getString(R.string.wish_you_good_fortune_and_every_success);
                }
                if (null == num || "".equals(num)) {
                    showToast(getResources().getString(R.string.please_import_correct_red_package_count));
                } else if (0 == Integer.parseInt(num)) {
                    showToast(getResources().getString(R.string.please_import_correct_red_package_count));
                } else {
                }*/
                payDialog.dismiss();
            }
        });
    }

    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(this).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payDialog.dismiss();
            }
        });
        payCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    dopaymoney(pwd);
                    //  validatePayPwd(pwd);
                }
            }
        });
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    //重写此方法解决AudioManager 导致的内存泄漏
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }
}
